// 仪表板组件

class DashboardComponent {
    constructor() {
        this.init();
    }
    
    init() {
        // 初始化仪表板页面
        this.initDashboardPage();
    }
    
    // 初始化仪表板页面
    initDashboardPage() {
        // 绑定事件
        this.bindEvents();
        
        // 加载仪表板数据
        this.loadDashboardData();
    }
    
    bindEvents() {
        // 可以在这里绑定仪表板相关的事件
    }
    
    // 加载仪表板数据
    async loadDashboardData() {
        try {
            const token = localStorage.getItem('authToken');
            if (!token) {
                console.error('用户未登录');
                return;
            }
            
            // 显示加载状态
            this.showLoadingIndicator(true);
            
            // 获取账单统计数据
            const statsResponse = await fetch('http://localhost:3003/api/bills/stats', {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                }
            });
            
            if (!statsResponse.ok) {
                throw new Error(`HTTP error! status: ${statsResponse.status}`);
            }
            
            const statsData = await statsResponse.json();
            
            // 渲染仪表板数据
            this.renderDashboard(statsData);
        } catch (error) {
            console.error('加载仪表板数据失败:', error);
            this.showMessage('加载数据失败，请稍后重试', 'error');
        } finally {
            // 隐藏加载状态
            this.showLoadingIndicator(false);
        }
    }
    
    // 渲染仪表板
    renderDashboard(data) {
        // 更新首页的本月概览
        this.updateHomePageOverview(data);
        
        // 更新仪表板页面的数据
        this.updateDashboardPage(data);
    }
    
    // 更新首页的本月概览
    updateHomePageOverview(data) {
        const { summary } = data;
        
        // 查找首页概览卡片中的数据元素
        const homePage = document.getElementById('homePage');
        if (!homePage) return;
        
        // 更新总收入
        const incomeElements = homePage.querySelectorAll('#userHomeContent .dashboard .card.neon-border:nth-child(1) p');
        if (incomeElements.length > 0) {
            incomeElements[0].textContent = `¥${summary.total_income.toFixed(2)}`;
        }
        
        // 更新总支出
        const expenseElements = homePage.querySelectorAll('#userHomeContent .dashboard .card.neon-border:nth-child(2) p');
        if (expenseElements.length > 0) {
            expenseElements[0].textContent = `¥${summary.total_expense.toFixed(2)}`;
        }
        
        // 更新结余
        const balanceElements = homePage.querySelectorAll('#userHomeContent .dashboard .card.neon-accent:nth-child(3) p');
        if (balanceElements.length > 0) {
            balanceElements[0].textContent = `¥${summary.net_income.toFixed(2)}`;
        }
    }
    
    // 更新仪表板页面的数据
    updateDashboardPage(data) {
        const { summary } = data;
        
        // 查找仪表板页面
        const dashboardPage = document.getElementById('dashboardPage');
        if (!dashboardPage) return;
        
        // 更新总收入
        const incomeElements = dashboardPage.querySelectorAll('.dashboard .card.neon-border:nth-child(1) p');
        if (incomeElements.length > 0) {
            incomeElements[0].textContent = `¥${summary.total_income.toFixed(2)}`;
            // 更新增长率（这里简化处理，实际应该计算环比增长率）
            if (incomeElements.length > 1) {
                incomeElements[1].textContent = `较上月 ${summary.income_count > 0 ? '+5.2%' : '0.0%'}`;
            }
        }
        
        // 更新总支出
        const expenseElements = dashboardPage.querySelectorAll('.dashboard .card.neon-border:nth-child(2) p');
        if (expenseElements.length > 0) {
            expenseElements[0].textContent = `¥${summary.total_expense.toFixed(2)}`;
            // 更新增长率（这里简化处理，实际应该计算环比增长率）
            if (expenseElements.length > 1) {
                expenseElements[1].textContent = `较上月 ${summary.expense_count > 0 ? '+2.1%' : '0.0%'}`;
            }
        }
        
        // 更新结余
        const balanceElements = dashboardPage.querySelectorAll('.dashboard .card.neon-accent:nth-child(3) p');
        if (balanceElements.length > 0) {
            balanceElements[0].textContent = `¥${summary.net_income.toFixed(2)}`;
            // 更新储蓄率
            if (balanceElements.length > 1) {
                const savingsRate = summary.total_income > 0 ? 
                    ((summary.total_income - summary.total_expense) / summary.total_income * 100) : 0;
                balanceElements[1].textContent = `储蓄率 ${savingsRate.toFixed(1)}%`;
            }
        }
    }
    
    // 显示/隐藏加载指示器
    showLoadingIndicator(show) {
        // 查找仪表板页面的加载指示器
        const dashboardPage = document.getElementById('dashboardPage');
        if (dashboardPage) {
            const loadingIndicator = dashboardPage.querySelector('.loading-indicator');
            if (loadingIndicator) {
                loadingIndicator.style.display = show ? 'block' : 'none';
            }
        }
    }
    
    // 显示消息
    showMessage(message, type) {
        // 创建消息元素
        const messageEl = document.createElement('div');
        messageEl.className = `message message-${type}`;
        messageEl.textContent = message;
        
        // 添加样式
        Object.assign(messageEl.style, {
            position: 'fixed',
            top: '20px',
            right: '20px',
            padding: '15px 20px',
            borderRadius: '5px',
            color: 'white',
            fontWeight: 'bold',
            zIndex: '1000',
            boxShadow: '0 2px 10px rgba(0,0,0,0.3)',
            transition: 'opacity 0.3s'
        });
        
        if (type === 'success') {
            messageEl.style.backgroundColor = '#4CAF50';
        } else if (type === 'info') {
            messageEl.style.backgroundColor = '#2196F3';
        } else {
            messageEl.style.backgroundColor = '#F44336';
        }
        
        // 添加到页面
        document.body.appendChild(messageEl);
        
        // 3秒后淡出并移除
        setTimeout(() => {
            messageEl.style.opacity = '0';
            setTimeout(() => {
                if (messageEl.parentNode) {
                    messageEl.parentNode.removeChild(messageEl);
                }
            }, 300);
        }, 3000);
    }
}

// 初始化仪表板组件
document.addEventListener('DOMContentLoaded', () => {
    window.dashboardComponent = new DashboardComponent();
});